import { type UserConfigExport, defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' // 需同时安装fast-glob => npm i fast-glob
import eslintPlugin from 'vite-plugin-eslint'
import { fileURLToPath, URL } from 'node:url'
import { createHtmlPlugin } from 'vite-plugin-html'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, fileURLToPath(new URL('./', import.meta.url)))
  const outDir = 'museum-management-web'
  const settingConfig: UserConfigExport = {
    plugins: [
      vue(),
      createSvgIconsPlugin({
        iconDirs: [fileURLToPath(new URL('./src/icons/svg', import.meta.url))],
        symbolId: 'icon-[name]'
      }),
      eslintPlugin({
        include: ['src/**/*.ts', 'src/**/*.js', 'src/**/*.vue', 'src/*.ts', 'src/*.js', 'src/*.vue'],
        cache: false
      }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            title: env['VITE_APP_TITLE']
          }
        }
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@st': fileURLToPath(new URL('./src/plugins/stratocirri-plus', import.meta.url))
      }
    },
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      },
      preprocessorOptions: {
        scss: {
          additionalData: ['@use "./src/styles/mixin.scss" as *;'].join('')
        }
      }
    },
    base: './', // 新增
    server: {
      host: true,
      proxy: {
        '/xpyunopenapi': {
          target: 'https://open-barcode.xpyun.net/api/openapi',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/xpyunopenapi/, '')
        }
      }
    },
    build: {
      outDir,
      commonjsOptions: {
        include: 'ckeditor5-custom-build/build/ckeditor'
      }
    },
    optimizeDeps: {
      include: ['ckeditor5-custom-build/build/ckeditor']
    }
  }
  if (mode === 'production') {
    settingConfig.build = {
      outDir,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      }
    }
  }
  return settingConfig
})
